import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * 
 */

/**
 * @author Navin
 * 
 */
public final class crypt {

	public static Object deserialize(InputStream in) {
		Object obj = null;
		try {
			ObjectInputStream objStream = new ObjectInputStream(in);
			obj = objStream.readObject();
			objStream.close();

		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		}
		return obj;
	}

	/**
	 * only for testing
	 * 
	 * @param args
	 * @throws IOException
	 */
	@SuppressWarnings("serial")
	public static void main(String[] args) throws IOException {

		byte rand = (byte) (Math.random() * 1000000000);
		ArrayList<Byte> RandList = new ArrayList<Byte>() {
			{
				for (int i = 0; i < 100; i++)
					add((byte) (Math.random() * 1000000000));
			}
		};
		System.out.println(RandList);

		InputStream serial = crypt.Serialize(RandList);
		Collection<Byte> coll = crypt.toCollection(serial);

		System.out.println(crypt.xor(coll, rand));

		serial = crypt.Serialize(RandList);
		coll = crypt.toCollection(serial);

		System.out.println(crypt.xor(coll, rand));

		System.out.println(rand);

		System.out.print(RandList.get(0) ^ rand);

		// System.out.println(crypt.xor(crypt.xor(coll, rand), rand));
	}

	public static InputStream Serialize(Serializable obj) {
		IOBlock iob = new IOBlock();
		ObjectOutputStream out = null;
		try {
			out = new ObjectOutputStream(iob.getOutputStream());
			out.writeObject(obj);
			out.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return iob.getInputStream();
	}

	public static Collection<Byte> toCollection(InputStream b)
			throws IOException {
		int last = -1;
		List<Byte> lst = new ArrayList<Byte>();
		while (true) {
			last = b.read();
			if (last == -1)
				return lst;
			lst.add((byte) last);
		}
	}

	public static Collection<Byte> xor(Collection<Byte> b, byte key) {
		Iterator<Byte> iter = b.iterator();
		ArrayList<Byte> AList = new ArrayList<Byte>();
		while (iter.hasNext())
			AList.add((byte) (iter.next() ^ key));
		return AList;
	}

}
